package service.employee.managers;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;

import employee.entities.EmployeeVO;
import employee.exceptions.IncompleteEmployeeException;
import employee.interfaces.EmployeeRemoteMgt;
import service.Factory;
import service.article.exceptions.ProxyException;
import service.employee.interfaces.EmployeeProxyMgt;

public class EmployeeProxyMgr implements EmployeeProxyMgt {

	private static EmployeeProxyMgr instance;

	private EmployeeProxyMgr() {
	}

	public static EmployeeProxyMgr getInstance() {
		if (instance == null)
			instance = new EmployeeProxyMgr();
		return instance;
	}

	@Override
	public EmployeeVO[] getEmployees() throws RemoteException, ProxyException {
		EmployeeRemoteMgt aux = this.getClientRemoteMgt();
		return aux.getEmployees();
	}

	@Override
	public EmployeeVO getEmployee(int id) throws RemoteException,
			ProxyException {
		EmployeeRemoteMgt aux = this.getClientRemoteMgt();
		return aux.getEmployee(id);
	}

	@Override
	public void update(EmployeeVO emp) throws RemoteException, ProxyException,
			IncompleteEmployeeException {
		this.getClientRemoteMgt().update(emp);
	}

	@Override
	public void delete(int id) throws RemoteException, ProxyException {
		this.getClientRemoteMgt().delete(id);
	}

	@Override
	public void add(EmployeeVO emp) throws RemoteException, ProxyException,
			IncompleteEmployeeException {
		this.getClientRemoteMgt().add(emp);

	}

	@Override
	public boolean authenticate(EmployeeVO emp, String pass)
			throws RemoteException, ProxyException, IncompleteEmployeeException {
		return this.getClientRemoteMgt().authenticate(emp, pass);
	}

	public EmployeeRemoteMgt getClientRemoteMgt() throws ProxyException {
		String employeeName = Factory.getInstance().getEmployee();
		EmployeeRemoteMgt temp = null;
		Registry oRegitry;
		try {
			oRegitry = Factory.getInstance().getRegistry();
			temp = (EmployeeRemoteMgt) oRegitry.lookup(employeeName);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		if (temp == null)
			throw new ProxyException("Error en el RMI");
		return temp;
	}

}
